import {celebrate, Joi} from "celebrate";
import {Request} from "express";
import * as express from "express";
import {DeliveryModel} from "../database/models/delivery";
import {RechargeModel} from "../database/models/recharge";
import {InternalError} from "./error";
import {Response, withDelivery} from "./middlewareType";
import {jwtAuthMiddleware} from "./passort";

const router = express.Router()

router.get('/',
  jwtAuthMiddleware,
  async (req: Request & withDelivery, res: Response) => {
    try {
      const delivery = await DeliveryModel.find()
        .lean()

      res.json({ok: true, data: {delivery}})
    } catch (e) {
      res.error(e)
    }
  })

router.get('/:deliveryId',
  celebrate({
    params: Joi.object({
      deliveryId: Joi.string().required()
    })
  }),
  async (req, res: Response) => {
    try {
      const delivery = await RechargeModel.findById(req.params.deliveryId)
        .lean()

      if (!delivery)
        throw InternalError("ALREADY_IN_DELIVERY")

      res.json({ok: true, data: {delivery}})
    } catch (e) {
      res.error(e)
    }
  })

export default router
